Here is one correct answer:
public static void main ( String[] args ) { Goods toy ; Taxable tax = new Toy ( "Building Blocks", 1.49, 6 ); toy = (Toy)tax; toy.display(); System.out.println( "Tax: "+ ((Taxable)toy).calculateTax() ); }
The first type cast in the answer must cast tax
to a type
Goods
(or an ancestor).
The second must cast toy
to Taxable
or to
a class that implements Taxable
.
When you think about such problems, remember that at compile time objects do not exist. The compiler knows what methods are available with a reference variable based only on the type of the variable.
For example, in the above,
only the calculateTax()
method would be available with tax
.
At run time the object tax
points to has more methods avaialble.
To say this in the code, use a type cast.
Here is another possible answer:
public static void main ( String[] args ) { Goods toy ; Taxable tax = new Toy ( "Building Blocks", 1.49, 6 ); toy = (Goods)tax; toy.display(); System.out.println( "Tax: "+ ((Toy)toy).calculateTax() ); }
Is this answer correct?